#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：      operate_yaml.py
   Remark :         企业级 YAML 操作工具类
-------------------------------------------------
"""

import yaml
from pathlib import Path
from typing import Any, Optional, Union
import logging

# Configure logging
logging.basicConfig(
    level=logging.WARNING,
    format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
)
logger = logging.getLogger("YAMLHandler")

# 模块公开接口
__all__ = ["YAMLHandler", "yaml_handler"]


class YAMLHandler:
    """
    企业级 YAML 操作工具类
    提供读取、写入、格式化和验证 YAML 的统一接口。
    """

    @staticmethod
    def read_yaml_file(filepath: Union[str, Path]) -> Any:
        """
        读取 YAML 文件并解析为 Python 对象。

        :param filepath: YAML 文件路径
        :return: Python 对象（通常是 dict 或 list）
        :raises FileNotFoundError: 文件不存在
        :raises yaml.YAMLError: YAML 格式错误
        """
        filepath = Path(filepath)
        logger.debug(f"Reading YAML file: {filepath}")
        if not filepath.exists():
            logger.error(f"File not found: {filepath}")
            raise FileNotFoundError(f"File not found: {filepath}")

        try:
            with open(filepath, "r", encoding="utf-8") as file:
                data = yaml.safe_load(file)
                logger.debug(f"YAML file loaded successfully: {filepath}")
                return data
        except yaml.YAMLError as e:
            logger.error(f"Failed to parse YAML file: {filepath} | Error: {e}")
            raise

    @staticmethod
    def write_yaml_file(filepath: Union[str, Path], data: Any) -> None:
        """
        将 Python 对象写入 YAML 文件。

        :param filepath: YAML 文件路径
        :param data: Python 对象（通常是 dict 或 list）
        """
        filepath = Path(filepath)
        logger.info(f"Writing YAML to file: {filepath}")
        try:
            with open(filepath, "w", encoding="utf-8") as file:
                yaml.safe_dump(data, file, allow_unicode=True, default_flow_style=False)
                logger.debug(f"YAML file written successfully: {filepath}")
        except Exception as e:
            logger.error(f"Failed to write YAML to file: {filepath} | Error: {e}")
            raise

    @staticmethod
    def parse_yaml_string(yaml_string: str) -> Any:
        """
        将 YAML 字符串解析为 Python 对象。

        :param yaml_string: YAML 格式的字符串
        :return: Python 对象
        :raises yaml.YAMLError: YAML 格式错误
        """
        logger.info("解析 YAML 字符串")
        try:
            data = yaml.safe_load(yaml_string)
            logger.info("YAML 字符串解析成功")
            return data
        except yaml.YAMLError as e:
            logger.error(f"无法解析 YAML 字符串 | 错误: {e}")
            raise

    @staticmethod
    def serialize_to_yaml_string(data: Any) -> str:
        """
        将 Python 对象序列化为 YAML 格式字符串。

        :param data: Python 对象
        :return: YAML 格式的字符串
        """
        logger.info("Serializing Python object to YAML string")
        try:
            yaml_string = yaml.safe_dump(data, allow_unicode=True, default_flow_style=False)
            logger.debug("Python object serialized to YAML string successfully")
            return yaml_string
        except Exception as e:
            logger.error(f"Failed to serialize object to YAML string | Error: {e}")
            raise

    @staticmethod
    def pretty_print_yaml(data: Any) -> None:
        """
        格式化输出 YAML 数据到控制台。

        :param data: Python 对象（通常是 dict 或 list）
        """
        logger.info("Pretty printing YAML data")
        try:
            print(yaml.safe_dump(data, allow_unicode=True, default_flow_style=False))
        except Exception as e:
            logger.error(f"Failed to pretty print YAML data | Error: {e}")
            raise


# 全局实例化，便于外部调用
yaml_handler = YAMLHandler()

# 示例用法
if __name__ == "__main__":
    # 读取 YAML 文件
    try:
        data = yaml_handler.read_yaml_file("example.yaml")
        yaml_handler.pretty_print_yaml(data)
    except Exception as e:
        logger.error(e)

    # 写入 YAML 文件
    example_data = {
        "name": "Alice",
        "age": 30,
        "languages": ["English", "Chinese"],
        "details": {"hobby": "reading", "active": True},
    }
    try:
        yaml_handler.write_yaml_file("output.yaml", example_data)
    except Exception as e:
        logger.error(e)

    # YAML 字符串解析
    yaml_str = """
    user:
      name: Bob
      age: 25
    """
    try:
        parsed_data = yaml_handler.parse_yaml_string(yaml_str)
        logger.info(parsed_data)
    except Exception as e:
        logger.error(e)

    # 序列化 Python 对象为 YAML 字符串
    try:
        yaml_string = yaml_handler.serialize_to_yaml_string(example_data)
        logger.info(yaml_string)
    except Exception as e:
        logger.error(e)
